//
//  BKConsoleManager.m
//  DSLinPedia-OC
//
//  Created by luzz on 2021/10/29.
//  Copyright © 2021 DaShenLin Pharmaceutical Group. All rights reserved.
//

#import "BKConsoleManager.h"

@interface BKConsoleManager()

@property(nonatomic,copy)NSMutableString * log;

@end

@implementation BKConsoleManager
{
    dispatch_source_t _source;
}
static BKConsoleManager *sharedInstance = nil;
+(BKConsoleManager*)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[super allocWithZone:NULL] init];

    });
    return sharedInstance;
}
+ (id)allocWithZone:(NSZone *)zone
{
    return [self shareManager];
}
- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (void)start
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addBKConsoleLog:) name:BKConsoleAddLog object:nil];
}



- (void)addBKConsoleLog:(NSNotification *)notification
{
    if (notification) {
        if ([notification isKindOfClass:[NSNotification class]]) {
            if (notification.object) {
                [self addLogWithObject:notification.object];
            }
        }
    }
    
}

- (void)addLogWithObject:(id)object
{
    NSString * logStr;
    if ([object isKindOfClass:[NSString class]]) {
        logStr = object;
    }else if ([object isKindOfClass:[NSDictionary class]]||[object isKindOfClass:[NSArray class]]){
        NSError *error;
        NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&error];
        if (data && (error == nil)) {
            logStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        }
    }else if ([object isKindOfClass:[NSData class]]){
        NSData *data = (NSData *)object;
        logStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }else{
        logStr = [NSString stringWithFormat:@"%@",object];
    }
    
    if (logStr) {
        
        
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS"];
        NSString *dateString = [df stringFromDate:[NSDate date]];
        
        [self.log appendFormat:@"%@ %@\n",dateString,logStr];
        
        
    }
    
    
}

-(NSString *)getLog
{
    return [self.log copy];
}


-(void)clearLog
{
    [self.log setString:@""];
}



#pragma mark - lazy
- (NSMutableString *)log
{
    if (!_log) {
        _log = [[NSMutableString alloc] initWithString:@""];
    }
    return _log;
}

@end
